<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请人" prop="applicant">
        <user-select v-model="queryParams.applicant" multiple placeholder="请选择申请人" :max-show="1"></user-select>
      </el-form-item>
      <el-form-item label="申请单位" prop="applicantUnit">
        <treeselect v-model="queryParams.applicantUnit" :options="deptOptions" :show-count="true"
                    placeholder="请选择来档单位" style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="被导出人" prop="exportedPerson">
        <person-select v-model="queryParams.exportedPerson" multiple placeholder="请选择被导出人"
                       :max-show="1"></person-select>
      </el-form-item>
      <el-form-item label="档案类型" prop="fileType">
        <el-input
            v-model="queryParams.fileType"
            placeholder="请输入档案类型"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="applicantDate">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.applicantDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form v-if="false" label-width="68px">
      <el-form-item label="流程Key" prop="processKey">
        <el-input
            v-model="processKey"
            placeholder="请输入流程Key"
            clearable
            size="small"
            style="width:200px"
        />
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="exportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="申请人" align="center" prop="applicantName"/>
      <el-table-column label="申请单位" align="center" prop="applicantUnitName"/>
      <el-table-column label="被导出人" align="center" prop="exportedPersonName"/>
      <el-table-column label="申请时间" align="center" prop="applicantDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicantDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期时间" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程状态" align="center" prop="actBusinessStatus.status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.act_status" :value="scope.row.actBusinessStatus.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              v-if="scope.row.actBusinessStatus.status!=='draft'"
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改内网导出对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="1000px" append-to-body>
      <el-tabs type="border-card">
        <el-tab-pane label="业务单据" v-loading="loading">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="申请人" prop="applicant">
                  <user-select v-model="form.applicant" :disabled="isView" placeholder="请选择申请人"
                               :max-show="1"></user-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申请单位" prop="applicantUnit">
                  <treeselect v-model="form.applicantUnit" :disabled="isView" :options="deptOptions" :show-count="true"
                              placeholder="请选择申请单位"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="被导出人" prop="exportedPerson">
                  <person-select v-model="form.exportedPerson" :disabled="isView" placeholder="请选择被导出人"
                                 :max-show="1"></person-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="导出格式" prop="exportFormat">
                  <el-radio v-for="item in exportedFormatOptions" :disabled="isView" v-model="form.exportFormat"
                            :label="item.value"
                            :key="item.value">{{ item.label }}
                  </el-radio>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="导出类型" prop="exportType">
                  <el-select v-model="form.exportType" :disabled="isView" placeholder="请选择导出类型"
                             style="width: 100%" @change="exportTypeChange">
                    <el-option
                        v-for="item in exportTypeOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="档案类型" prop="fileType">
              <el-switch
                  :disabled="docOptions.length===0"
                  v-model="selectAllDoc"
                  active-text="全选"
                  inactive-text="取消"
                  @change="selectAllDocChangeHandel"
              >
              </el-switch>
              <el-tree
                  ref="docTree"
                  empty-text="请现选择被导出人"
                  :data="docOptions"
                  default-expand-all
                  check-on-click-node
                  @check="checkHandel"
                  show-checkbox
                  node-key="id"
                  :props="defaultProps">
              </el-tree>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="申请时间" prop="applicantDate">
                  <el-date-picker clearable size="small" style="width: 100%;"
                                  :disabled="isView"
                                  v-model="form.applicantDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择申请时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="到期时间" prop="endDate">
                  <el-date-picker clearable size="small" style="width: 100%;"
                                  :disabled="isView"
                                  v-model="form.endDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择到期时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :disabled="isView" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-form>
          <div class="dialog-footer" style="float:right" v-if="flag">
            <el-button :loading="buttonLoading" type="info" @click="submitForm('zancun')">暂 存</el-button>
            <el-button :loading="buttonLoading" type="primary" @click="submitForm('submit')">提 交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-tab-pane>
        <!-- 审批历史 -->
        <el-tab-pane label="审批历史" v-if="processInstanceId">
          <history ref="historyRef" :processInstanceId="processInstanceId"></history>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- 提交 -->
    <verify ref="verifyRef" @submitCallback="submitCallback" :taskId="taskId" :taskVariables="taskVariables"
            :sendMessage="sendMessage"></verify>
  </div>
</template>

<script>
import {getExport, listExport, sendToDisk} from "@/api/business/export";
import UserSelect from "@/components/UserSelect/index.vue";
import PersonSelect from "@/components/PersonSelect/index.vue";
import {treeselect} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import history from "@/components/Process/History";
import verify from "@/components/Process/Verify";
import {mapGetters} from "vuex";
import {getExportType, listExportType} from "@/api/business/exportType";
import {personFileTree} from "@/api/business/personFile";
import {getAllIds} from "@/utils/tree";

export default {
  name: "Export",
  dicts: ['act_status'],
  components: {
    Treeselect, UserSelect,
    PersonSelect,
    history,
    verify
  },
  computed: {
    ...mapGetters(['userInfo']),
    docOptionsIds: function () {
      return getAllIds(this.docOptions, 'id');
    }
  },
  watch: {
    'form.exportedPerson': function (newVal, oldVal) {
      if (newVal) {
        this.getDocOptions(newVal);
      } else {
        this.docOptions = []
      }
    }
  },
  data() {
    return {
      // 流程实例
      processInstanceId: '',
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //档案类型
      docOptions: [],
      exportTypeOptions: [],
      selectDocOptions: [],
      exportedFormatOptions: [
        {
          value: '0',
          label: '文件夹导出'
        },
        {
          value: '2',
          label: '合并导出'
        }
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 总条数
      total: 0,
      // 内网导出表格数据
      exportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selectAllDoc: 0,
      // 部门树选项
      deptOptions: [],
      isView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicant: null,
        applicantUnit: null,
        exportedPerson: null,
        fileType: null,
        applicantDate: null,
        exportType: null,
        exportFormat: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        applicant: [
          {required: true, message: "申请人不能为空", trigger: "blur"}
        ],
        applicantUnit: [
          {required: true, message: "申请单位不能为空", trigger: "blur"}
        ],
        exportedPerson: [
          {required: true, message: "申请单位不能为空", trigger: "blur"}
        ],
        applicantDate: [
          {required: true, message: "申请时间不能为空", trigger: "blur"}
        ],
        endDate: [
          {required: true, message: "到期时间不能为空", trigger: "blur"}
        ],
      },
      taskVariables: {}, //流程变量
      taskId: undefined, //任务id
      flag: true,
      // 消息提醒
      sendMessage: {},
      processKey: 'IntranetExport'
    };
  },
  created() {
    this.getList();
  },
  methods: {
    checkHandel(node, data) {
      this.form.fileType = data.checkedKeys?.join(',');
    },
    canSend(row) {
      return row.actBusinessStatus.status === 'finish' && new Date().getTime() < new Date(row.endDate).getTime();
    },
    handleDown(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: '操作提示',
        message: h('p', null, [
              h('span', null, '审批结束时已将文件发送至内部网盘，请留意 '),
              h('i', {style: 'color: teal'}, '云桌面消息通知!'),
              h('span', null, '点击'),
              h('i', {style: 'color: blue'}, '【继续】'),
              h('span', null, '将继续发送，并留意您的'),
              h('i', {style: 'color: red'}, '邮箱'),
              h('p', {style: 'color: red'}, 'tips:切勿频繁发送下载'),
            ]
        ),
        showCancelButton: true,
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '发送中...';
            sendToDisk(row.id).then(()=>{
              this.$message({
                type: 'success',
                message: '发送成功,请留意消息'
              });
            }).finally(() => {
              instance.confirmButtonLoading = false;
              done();
            });
          } else {
            done();
          }
        }
      })
    },
    /** 查询内网导出列表 */
    getList() {
      this.loading = true;
      this.getTreeselect();
      listExport(this.queryParams).then(response => {
        this.exportList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        applicant: this.userInfo.userId,
        applicantUnit: this.userInfo.dept.deptId,
        exportedPerson: null,
        fileType: null,
        exportFormat: null,
        exportType: null,
        applicantDate: null,
        endDate: null,
        status: null,
        approvalStatus: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.processInstanceId = undefined
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //查看
    handleView(row) {
      this.flag = false
      this.loading = true;
      this.isView = true;
      this.getExportTypeOptions();
      this.selectDocOptions = [];
      this.reset();
      const id = row.id || this.ids
      getExport(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.$nextTick(() => {
          this.processInstanceId = response.data.actBusinessStatus.processInstanceId
        })
        let fileTypeIds = response.data.fileType.split(',');
        for (let i = 0; i < fileTypeIds.length; i++) {
          this.selectDocOptions.push(Number(fileTypeIds[i]));
        }
        this.open = true;
        this.title = "查看内网导出";
      });
    },
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getDocOptions(personId) {
      personFileTree(personId).then(response => {
        this.docOptions = response.data;
      }).then(() => {
        this.$refs.docTree.setCheckedKeys(this.form.fileType.split(','))
      })
    },
    getExportTypeOptions() {
      listExportType().then(response => {
        this.exportTypeOptions = response.rows;
      })
    },
    exportTypeChange() {
      if (this.form.exportType) {
        this.selectDocOptions = [];
        getExportType(this.form.exportType).then(response => {
          let typeId = response.data.typeId.split(',');
          for (let i = 0; i < typeId.length; i++) {
            this.selectDocOptions.push(Number(typeId[i]));
          }
          this.$refs.docTree.setCheckedKeys(this.selectDocOptions);
        });
      }
    },
    selectAllDocChangeHandel(value) {
      if (value) {
        this.$refs.docTree.setCheckedKeys(this.docOptionsIds)
      } else {
        this.$refs.docTree.setCheckedKeys([]);
      }
    }
  }
};
</script>
